package com.vxdata.utils.modules.utils.culture;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 文件夹压缩
 */
public class DownloadZipUtil {
    private static final int BUFFER_SIZE = 4 * 1024;

    /**
     * 新版目录级别的文件压缩
     *
     * @param fileUrl          文件路径
     * @param out
     * @param KeepDirStructure
     */
    public static void toZipNew(String fileUrl, OutputStream out, boolean KeepDirStructure) {
        ZipOutputStream zos = null;
        try {
            zos = new ZipOutputStream(out);
            File file = new File(fileUrl);
            compress(file, zos, file.getName(), KeepDirStructure);
        } catch (Exception e) {
            throw new RuntimeException("zip error from ZipUtils", e);
        } finally {
            if (zos != null) {
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    /**
     * 把文件打成压缩包并输出到客户端浏览器中
     *
     * @param response    客户端响应
     * @param srcFiles    所有要压缩的文件的路径
     * @param zipFileName 压缩包的名称
     */
    public static void downloadZipFiles(HttpServletResponse response, List<String> srcFiles, String zipFileName) {
        try {
            response.reset(); // 重点突出
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/zip");
            // 对文件名进行编码处理中文问题
            zipFileName = new String(zipFileName.getBytes(), StandardCharsets.UTF_8);
            response.setHeader("Content-Disposition", "attachment;filename=" + zipFileName);

            // --设置成这样可以不用保存在本地，再输出， 通过response流输出,直接输出到客户端浏览器中。
            ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
            zipFile(srcFiles, zos);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 递归压缩文件
     *
     * @param filePaths 需要压缩的文件路径集合
     * @throws IOException
     */
    private static void zipFile(List<String> filePaths, ZipOutputStream zos) {
        //设置读取数据缓存大小
        byte[] buffer = new byte[4096];
        try {
            //循环读取文件路径集合，获取每一个文件的路径
            for (String filePath : filePaths) {
                File inputFile = new File(filePath);
                //判断文件是否存在
                if (inputFile.exists()) {
                    //判断是否属于文件，还是文件夹
                    if (inputFile.isFile()) {
                        //创建输入流读取文件
                        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(inputFile));
                        //将文件写入zip内，即将文件进行打包
                        zos.putNextEntry(new ZipEntry(inputFile.getName()));
                        //写入文件的方法，同上
                        int size = 0;
                        //设置读取数据缓存大小
                        while ((size = bis.read(buffer)) > 0) {
                            zos.write(buffer, 0, size);
                        }
                        //关闭输入输出流
                        zos.closeEntry();
                        bis.close();
                    } else {  //如果是文件夹，则使用穷举的方法获取文件，写入zip
                        File[] files = inputFile.listFiles();
                        List<String> filePathsTem = new ArrayList<String>();
                        for (File fileTem : files) {
                            filePathsTem.add(fileTem.toString());
                        }
                        zipFile(filePathsTem, zos);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != zos) {
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) throws IOException {
        long start = System.currentTimeMillis();
        List<String> urlList = new ArrayList<>();
        urlList.add("D:\\vxdata\\uploadPath\\download\\2022823");
        ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream("D:\\vxdata\\uploadPath\\download\\2022823.zip"));
        zipFile(urlList, zipOutputStream);

        long end = System.currentTimeMillis();
        System.out.println(end - start);

    }


    /**
     * 符合多级文件目录的递归压缩
     *
     * @param sourceFile
     * @param zipOutputStream
     * @param name
     * @param KeepDirStructure
     * @throws Exception
     */
    private static void compress(File sourceFile, ZipOutputStream zipOutputStream, String name, boolean KeepDirStructure) throws Exception {
        byte[] buf = new byte[BUFFER_SIZE];
        if (sourceFile.isFile()) {
            zipOutputStream.putNextEntry(new ZipEntry(name));
            int len;
//            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(sourceFile));
            FileInputStream in = new FileInputStream(sourceFile);
            while ((len = in.read(buf)) != -1) {
                zipOutputStream.write(buf, 0, len);
            }
            zipOutputStream.closeEntry();
            in.close();
//            bis.close();
        } else {
            File[] listFiles = sourceFile.listFiles();
            if (listFiles == null || listFiles.length == 0) {
                if (KeepDirStructure) {
                    zipOutputStream.putNextEntry(new ZipEntry(name + "/"));
                    zipOutputStream.closeEntry();
                }
            } else {
                for (File listFile : listFiles) {
                    if (KeepDirStructure) {
                        compress(listFile, zipOutputStream, name + "/" + listFile.getName(), KeepDirStructure);
                    } else {
                        compress(listFile, zipOutputStream, listFile.getName(), KeepDirStructure);
                    }
                }
            }
        }
    }

}
